﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Security.Principal;

namespace SimpleSocxs
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            var path = Helper.MapPath("~/datastore.bin");
            if (File.Exists(path))
            {
                var formatter = new BinaryFormatter();
                using (Stream stream = new FileStream(Helper.MapPath("~/datastore.bin"), FileMode.Open))
                {
                    SocxsDataStore._current = (SocxsDataStore)formatter.Deserialize(stream);                    
                }
            }
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            IPrincipal user = HttpContext.Current.User;
            if (user != null && user.Identity is FormsIdentity && user.Identity.IsAuthenticated)
            {
                var socxs_user = SocxsDataStore.Current.GetUserByName(user.Identity.Name);
                if (socxs_user == null)
                {
                    FormsAuthentication.SignOut();
                }                

                HttpContext.Current.User = socxs_user;
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            if (SocxsDataStore.Current != null)
            {
                var formatter = new BinaryFormatter();
                using (Stream stream = new FileStream(Helper.MapPath("~/datastore.bin"), FileMode.OpenOrCreate))
                {
                    formatter.Serialize(stream, SocxsDataStore.Current);
                }
            }
        }
    }
}